package com.fimmlps.reronge.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fimmlps.reronge.dto.*;
import com.fimmlps.reronge.entity.*;
import com.fimmlps.reronge.service.*;
import com.fimmlps.reronge.vo.TResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@RestController
@RequestMapping("/actorSingle")
public class ActorSingleController {
    @Autowired
    private IActorSingleService singleService;

    @Autowired
    private IEntryUserService userService;

    @Autowired
    private IActorCommentService commentService;

    @Autowired
    private IActorImgurlService imgurlService;


    public List<EntryCommentDto> spawnCommentDtoList(List<ActorComment> commentList){
        HashMap<Integer,EntryCommentDto> baseMap = new HashMap<>();
        List<EntryCommentDto> cdtoList = new ArrayList<>();
        List<EntryCommentDto> replyLists = new ArrayList<>();
        for(ActorComment comment:commentList){
            EntryCommentDto cdto = new EntryCommentDto(comment);
            EntryUser user = userService.getById(comment.getUserId());
            if(user!=null){
                cdto.setUserName(user.getUserName());
                cdto.setUserHeadUrl(user.getUserHeadUrl());
            }
            if(cdto.getEntryCommentTopId()!=null&&cdto.getEntryCommentTopId()>0){
                replyLists.add(cdto);
            }
            else {
                cdtoList.add(cdto);
                baseMap.put(cdto.getEntryCommentId(),cdto);
            }
        }
        //添加reply
        for(EntryCommentDto dto:replyLists){
            EntryCommentDto baseDto = baseMap.get(dto.getEntryCommentTopId());
            if(baseDto!=null){
                baseDto.getReplyList().add(dto);
            }
        }
        return cdtoList;
    }

    //
    public ActorSingleDto spawnSingleDto(ActorSingle single){
        ActorSingleDto dto = new ActorSingleDto(single);
        //IMG URL
        ArrayList<String> urls = new ArrayList<>();
        List<ActorImgurl> aiList = imgurlService.list(new QueryWrapper<ActorImgurl>().eq("actor_single_id",dto.getActorSingleId()));
        for(ActorImgurl ai:aiList)
            urls.add(ai.getImgUrl());
        dto.setImgUrls(urls);
        EntryUser user = userService.getById(dto.getUserId());
        if(user!=null){
            dto.setUserName(user.getUserName());
        }
        return dto;
    }

    public List<ActorSingleDto> spawnSingleDtoList(List<ActorSingle> totals){
        List<ActorSingleDto> dtoList = new ArrayList<>();
        for(int i =0;i<totals.size();i++){
            dtoList.add(spawnSingleDto(totals.get(i)));
        }
        return dtoList;
    }

    //POST 获取最近一个月最热门的N篇文章
    //参数： pageIndex （页面号，从1开始） pageSize（页面大小）
    @PostMapping("/getRecentHottestActorsByPage")
    public TResponseVo<PageASingleDto> getRecentHottestActorsByPage(@RequestBody Map<String,Object> map){
        try {
            int index = (int) map.get("pageIndex");
            int pageSize = (int) map.get("pageSize");
            Logger.getGlobal().info("Actor页面信息，页号："+index + "；页面大小："+pageSize);
            QueryWrapper<ActorSingle> newest = new QueryWrapper<>();
            LocalDateTime oneMonthAgo = LocalDateTime.now().minusMonths(1);
            newest.ge("update_time",oneMonthAgo);
            newest.orderByDesc("clicks").orderByDesc("update_time");
            Page<ActorSingle> page = new Page<>(index,pageSize);
            IPage<ActorSingle> iPage = singleService.page(page,newest);
            List<ActorSingle> totals = iPage.getRecords();

            List<ActorSingleDto> dtoList = spawnSingleDtoList(totals);
            return TResponseVo.success(new PageASingleDto(index,dtoList.size(),dtoList));

        }catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }
    }


    //POST 按最新时间顺序分页获取
    //参数： pageIndex （页面号，从1开始） pageSize（页面大小）
    @PostMapping("/getNewestActorsByPage")
    public TResponseVo<PageASingleDto> getNewestActorsByPage(@RequestBody Map<String,Object> map){
        try {
            int index = (int) map.get("pageIndex");
            int pageSize = (int) map.get("pageSize");
            Logger.getGlobal().info("Actor页面信息，页号："+index + "；页面大小："+pageSize);
            QueryWrapper<ActorSingle> newest = new QueryWrapper<>();
            newest.orderByDesc("update_time");
            Page<ActorSingle> page = new Page<>(index,pageSize);
            IPage<ActorSingle> iPage = singleService.page(page,newest);
            List<ActorSingle> totals = iPage.getRecords();

            List<ActorSingleDto> dtoList = spawnSingleDtoList(totals);
            return TResponseVo.success(new PageASingleDto(index,dtoList.size(),dtoList));

        }catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }
    }

    //POST 按最多点击顺序分页获取
    //参数： pageIndex （页面号，从1开始） pageSize（页面大小）
    @PostMapping("/getHottestActorsByPage")
    public TResponseVo<PageASingleDto> getHottestActorsByPage(@RequestBody Map<String,Object> map){
        try {
            int index = (int) map.get("pageIndex");
            int pageSize = (int) map.get("pageSize");
            Logger.getGlobal().info("Actor页面信息，页号："+index + "；页面大小："+pageSize);
            QueryWrapper<ActorSingle> hottest = new QueryWrapper<>();
            hottest.orderByDesc("clicks");
            Page<ActorSingle> page = new Page<>(index,pageSize);
            IPage<ActorSingle> iPage = singleService.page(page,hottest);
            List<ActorSingle> totals = iPage.getRecords();

            List<ActorSingleDto> dtoList = spawnSingleDtoList(totals);
            return TResponseVo.success(new PageASingleDto(index,dtoList.size(),dtoList));

        }catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }
    }

    // *IMPORTANT
    //POST 根据词条ID进入词条页面，获取完整信息 包括本体、评论等 会触发clicks++的效果
    //参数 actorSingleId
    @PostMapping("/getActorSingleById")
    public TResponseVo<ActorSingleDto> getActorSingleById(@RequestBody Map<String,Object> map){
        try {
            int id = (int) map.get("actorSingleId");
            ActorSingle single = singleService.getById(id);
            if(single!=null){
                //clicks++
                single.setClicks(single.getClicks()+1);
                singleService.updateById(single);
                ActorSingleDto dto = spawnSingleDto(single);
                //comment
                List<ActorComment> commentList = commentService.list(new QueryWrapper<ActorComment>().eq("actor_single_id",id));
                if(commentList!=null){
                    dto.setComments(spawnCommentDtoList(commentList));
                }
                return TResponseVo.success(dto);
            }
            else {
                return TResponseVo.error(404,"没有获取到actorSingle");
            }

        }catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }
    }

    //IMPORTANT
    //POST 写文章
    //参数：用户名-userName 文章标题-title 文章内容-text
    @PostMapping("/writeActor")
    public TResponseVo<ActorSingleDto> writeActor(@RequestBody ActorWriteDto awDto){
        try {
            String userName = awDto.getUserName();
            String title = awDto.getTitle();
            String text = awDto.getText();
            ArrayList<String> urls = awDto.getUrls();
            EntryUser user = userService.getOne(new QueryWrapper<EntryUser>().eq("user_name",userName));
            if(user==null){
                return TResponseVo.error(400,"没有该用户！");
            }
            int userId = user.getUserId();
            ActorSingle single = new ActorSingle();
            single.setUserId(userId);
            single.setTitle(title);
            single.setContent(text);
            single.setClicks(0);
            single.setCreateTime(LocalDateTime.now());
            single.setUpdateTime(LocalDateTime.now());
            singleService.save(single);
            //save urls
            for(String s:urls){
                ActorImgurl ai = new ActorImgurl();
                ai.setActorSingleId(single.getActorSingleId());
                ai.setImgUrl(s);
                imgurlService.save(ai);
            }
            ActorSingleDto dto = new ActorSingleDto(single);
            dto.getImgUrls().addAll(urls);

            return new TResponseVo<>(200,dto,"说说发布成功");

        }catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }

    }

    //POST 修改文章（暂时不能修改图片）
    //参数：用户名-userName 文章ID-actorSingleId 文章标题-title 文章内容-text
    @PostMapping("/updateActor")
    public TResponseVo<ActorSingleDto> updateActor(@RequestBody ActorUpdateDto auDto){
        try {
            String userName = auDto.getUserName();
            int actorSingleId = auDto.getActorSingleId();
            String title = auDto.getTitle();
            String text = auDto.getText();
            EntryUser user = userService.getOne(new QueryWrapper<EntryUser>().eq("user_name",userName));
            if(user==null){
                return TResponseVo.error(400,"没有该用户！");
            }
            ActorSingle single = singleService.getById(actorSingleId);
            if(single==null){
                return TResponseVo.error(400,"没有该文章！");
            }
            single.setTitle(title);
            single.setContent(text);
            single.setUpdateTime(LocalDateTime.now());
            singleService.updateById(single);
            ActorSingleDto dto = spawnSingleDto(single);

            return TResponseVo.success(dto);

        }catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }
    }

    //POST 评论
    //参数 用户名-userName 词条id-entrySingleId 根评论id-entryCommentTopId 内容-text
    @PostMapping("/writeComment")
    public TResponseVo<EntryCommentDto> writeComment(@RequestBody Map<String,Object> map){
        try {
            String userName = (String) map.get("userName");
            int actorSingleId = (int)map.get("actorSingleId");
            int entryCommentTopId = (int)map.get("entryCommentTopId");
            String text = (String) map.get("text");
            EntryUser user = userService.getOne(new QueryWrapper<EntryUser>().eq("user_name",userName));
            if(user==null){
                return TResponseVo.error(400,"没有该用户！");
            }
            int userId = user.getUserId();
            ActorComment cmt = new ActorComment();
            cmt.setUserId(userId);
            cmt.setActorSingleId(actorSingleId);
            cmt.setActorCommentTopId(entryCommentTopId);
            cmt.setText(text);
            cmt.setCreateTime(LocalDateTime.now());
            commentService.save(cmt);
            EntryCommentDto dto = new EntryCommentDto(cmt);
            dto.setUserName(user.getUserName());
            dto.setUserHeadUrl(user.getUserHeadUrl());
            return new TResponseVo<>(200,dto,"评论/回复成功");

        } catch (Exception e){
            return TResponseVo.error(500,e.getMessage());
        }

    }

}
